#include "usersquota.h"
#include <QFile>
#include <QDir>
#include <QTextStream>
#include <QByteArray>
#include <QList>
#include <QDebug>

#define QUOTA_COUNT 7
static QByteArray quoEnd="end";
static char spacer=',';
static QString logpath="/home/lou/Openstack/log";
static QString temppath="/home/lou/Openstack/temp";

UsersQuota::UsersQuota()
{

}
UsersQuota::~UsersQuota()
{
    qDebug()<<"delete userQuota";
}

/*
 * Check if the user already exists
 * @param user:user name
 * return
*/
bool UsersQuota::checkIdentity(const QString& user,const QString& password)
{
    QFile fin(logpath+'/'+user+".log");
    if(!fin.exists())
    {
        return false;
    }
    if(!fin.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return false;
    }
    QByteArray line = fin.readLine();
    fin.close();
    QList<QByteArray> list=line.split(',');
    if(list.size()==QUOTA_COUNT&&list.at(1)==password)
    {
        return true;
    }
    return false;
}
bool UsersQuota::addAndGetQuota(const QString& user,int cpus,int ram,int disk,Quota& curQuota)
{
    return changeQuota(user,cpus,ram,disk,1,curQuota);
}
bool UsersQuota::cutAndGetQuota(const QString& user,int cpus,int ram,int disk,Quota& curQuota)
{
    return changeQuota(user,-cpus,-ram,-disk,-1,curQuota);
}
/*
 * change user's quota
 * @param user:user name
 * @param vcpus,ram,disk,vm: add or cut quota
 * return :quota now
*/
bool UsersQuota::changeQuota(const QString& user,int vcpus,int ram,int disk,int vm,Quota& quota)
{
    QFile fin(logpath+'/'+user+".log");
    if(!fin.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return false;
    }
    QByteArray line = fin.readLine();
    fin.close();
    QList<QByteArray> list=line.split(',');
    if(list.size()==QUOTA_COUNT)
    {
        int curVcpus=list.at(2).toInt()+vcpus;
        int curRam=list.at(3).toInt()+ram;
        int curDisk=list.at(4).toInt()+disk;
        int curVm=list.at(5).toInt()+vm;
        if(curVcpus<0||curRam<0||curDisk<0||curVm<0)
        {
            return false;
        }
        quota.user=list.at(0);
        quota.passwd=list.at(1);
        quota.vcups=QString::number(curVcpus);
        quota.ram=QString::number(curRam);
        quota.disk=QString::number(curDisk);
        quota.vmNum=QString::number(curVm);
        return true;
    }
    return false;
}
bool UsersQuota::saveQuota(Quota& quota)
{
    QFile fout(logpath+'/'+quota.user+".log");
    if(!fout.open(QIODevice::WriteOnly|QIODevice::Truncate))
    {
        return false;
    }
    QByteArray buffer;
    buffer.append(quota.user).append(spacer);
    buffer.append(quota.passwd).append(spacer);
    buffer.append(quota.vcups).append(spacer);
    buffer.append(quota.ram).append(spacer);
    buffer.append(quota.disk).append(spacer);
    buffer.append(quota.vmNum).append(spacer).append(quoEnd);
    fout.write(buffer);
    fout.close();
    return true;
}

